<template>
  <div ref="el" :class="className" :style="{ height, width }"></div>
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, nextTick } from 'vue'
import * as echarts from 'echarts'
import { debounce } from 'lodash-es'

// 引入 macarons 主题
import 'echarts/theme/macarons'

// 定义组件名称
defineOptions({
  name: 'PieChart',
})

// 定义组件属性
interface Props {
  className?: string
  width?: string
  height?: string
}

const props = withDefaults(defineProps<Props>(), {
  className: 'chart',
  width: '100%',
  height: '300px',
})

// 图表实例
const chart = ref<echarts.ECharts | null>(null)

// 获取 DOM 元素的引用
const el = ref<HTMLDivElement | null>(null)

// Resize 相关逻辑
let sidebarElm: HTMLElement | null = null
let resizeHandler: (() => void) | null = null

const $_sidebarResizeHandler = (e: TransitionEvent) => {
  if (e.propertyName === 'width' && resizeHandler) {
    resizeHandler()
  }
}

const initListener = () => {
  resizeHandler = debounce(() => {
    resize()
  }, 100)
  window.addEventListener('resize', resizeHandler)

  sidebarElm = document.getElementsByClassName('sidebar-container')[0] as HTMLElement
  sidebarElm &&
    sidebarElm.addEventListener('transitionend', $_sidebarResizeHandler as EventListener)
}

const destroyListener = () => {
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler)
    resizeHandler = null
  }

  if (sidebarElm) {
    sidebarElm.removeEventListener('transitionend', $_sidebarResizeHandler as EventListener)
    sidebarElm = null
  }
}

const resize = () => {
  if (chart.value) {
    chart.value.resize()
  }
}

// 初始化图表
const initChart = () => {
  if (el.value) {
    chart.value = echarts.init(el.value, 'macarons')

    chart.value.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)',
      },
      legend: {
        left: 'center',
        bottom: '10',
        data: ['Industries', 'Technology', 'Forex', 'Gold', 'Forecasts'],
      },
      series: [
        {
          name: 'WEEKLY WRITE ARTICLES',
          type: 'pie',
          roseType: 'radius',
          radius: [15, 95],
          center: ['50%', '38%'],
          data: [
            { value: 320, name: 'Industries' },
            { value: 240, name: 'Technology' },
            { value: 149, name: 'Forex' },
            { value: 100, name: 'Gold' },
            { value: 59, name: 'Forecasts' },
          ],
          animationEasing: 'cubicInOut',
          animationDuration: 2600,
        },
      ],
    })
  }
}

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    initChart()
    initListener()
  })
})

onBeforeUnmount(() => {
  if (!chart.value) {
    return
  }
  chart.value.dispose()
  chart.value = null
  destroyListener()
})
</script>
